import { createRouter, createWebHashHistory } from 'vue-router'
import routesConfig from './router'
import store from '@/store'
// 创建路由器
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      name: 'login', //命名路由
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      name: 'layout', //命名路由
    },
  ],
  // 滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    }
  },
})

// 动态添加路由
const configRouter = () => {
  if (!router.hasRoute("layout")) {
    router.addRoute({
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      name: 'layout', //命名路由
    })
  }
  routesConfig.forEach((item) => {
    checkPrimission(item) && router.addRoute('layout', item)
  })
  // 改变vuex中isGetterRouter为true
  store.commit('changeGetterRouter', true)
}

const checkPrimission = (item: any) => {
  if (item.requireAdmin) {
    // @ts-ignore
    return store.state.userInfo.role == 0
  }
  return true
}


// 路由拦截,每次路由跳转之前，都会执行
// @ts-expect-error
router.beforeEach((to, from, next) => {
  if (to.name == 'login') {
    next()
  } else {
    if (!localStorage.getItem('token')) {
      next({
        path: '/login',
      })
    } else {
      if (!store.state.isGetterRouter) {
        // 删除所有嵌套路由
        // 删除layout
        router.removeRoute("layout")
        configRouter()
        next({
          path: to.fullPath,
        })
      } else {
        next()
      }
    }
  }
})

export default router
